package com.erp.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;
import org.apache.log4j.Logger;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

/**
 * word工具类
 *
 * @Author lst
 * @Date 2020-06-22 19:53
 * @Version 1.0
 **/
public class WordUtils {

    /**
     * 日志
     */
    private static final Logger LOGGER = Logger.getLogger(WordUtils.class);

    /**
     * 通过模板导出word
     *
     * @param dataMap          封装的数据信息
     * @param templateFilePath 模板文件路径
     * @param templateFileName 模板文件名称
     * @param outFilePath      导出的word路径
     */
    public static  void exportWordByTemplate(Map<String, Object> dataMap, String templateFilePath, String templateFileName, String outFilePath) {
        try {
            LOGGER.info("开始通过模板导出word");
            //Configuration 用于读取ftl文件
            Configuration configuration = new Configuration(new Version("2.3.23"));
            configuration.setDefaultEncoding("utf-8");
            configuration.setDirectoryForTemplateLoading(new File(templateFilePath));
            //输出文档路径及名称
            File outFile = new File(outFilePath);
            //以utf-8的编码读取ftl文件
            Template template = configuration.getTemplate(templateFileName, "utf-8");
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
            template.process(dataMap, out);
            out.close();
            LOGGER.info("成功通过模板导出word");
        } catch (Exception e) {
            LOGGER.warn("通过模板导出word异常:" + e);
            e.printStackTrace();
        }

    }

    /**
     * 通过模板导出word
     *
     * @param dataMap          封装的数据信息
     * @param templateFilePath 模板文件路径
     * @param templateFileName 模板文件名称
     * @param
     */
    public static  void exportWordByTemplate(Map<String, Object> dataMap, String templateFilePath, String templateFileName, HttpServletResponse response) {
        PrintWriter out =null;
        try {
             out =response.getWriter();
            LOGGER.info("开始通过模板导出word");
            //Configuration 用于读取ftl文件
            Configuration configuration = new Configuration(new Version("2.3.23"));
            configuration.setDefaultEncoding("utf-8");
            configuration.setDirectoryForTemplateLoading(new File(templateFilePath));
            //输出文档路径及名称
          //  File outFile = new File(outFilePath);
            //以utf-8的编码读取ftl文件
            Template template = configuration.getTemplate(templateFileName, "utf-8");
          //  Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);

            template.process(dataMap, out);

            LOGGER.info("成功通过模板导出word");
        } catch (Exception e) {
            LOGGER.warn("通过模板导出word异常:" + e);
            e.printStackTrace();
        }finally {
            try {
                if (out != null)
                    out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
    /**
     * 获得图片的Base64编码
     * @param imgFile
     * @return
     * @Author Huang Xiaocong 2018年12月15日 下午10:15:10
     */
    public static String getImageStr(String imgFile) {
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(imgFile);
        } catch (FileNotFoundException e) {

            e.printStackTrace();
        }
        try {
            data = new byte[in.available()];
            //注：FileInputStream.available()方法可以从输入流中阻断由下一个方法调用这个输入流中读取的剩余字节数
            in.read(data);
            in.close();
        } catch (IOException e) {

            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);

    }
    //base64转化工具
    public static String GetImageStrFromUrl(String imgURL) {

        byte[] data=null;
        try {
            // 创建URL
            URL url = new URL(imgURL);
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            //超时响应时间为5秒
            conn.setConnectTimeout(5 * 1000);
            //通过输入流获取图片数据
            InputStream inStream = conn.getInputStream();
            //得到图片的二进制数据，以二进制封装得到数据，具有通用性
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            //创建一个Buffer字符串
            byte[] buffer = new byte[1024];
            //每次读取的字符串长度，如果为-1，代表全部读取完毕
            int len = 0;
            //使用一个输入流从buffer里把数据读取出来
            while ((len = inStream.read(buffer)) != -1) {
                //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
                outStream.write(buffer, 0, len);
            }
            //关闭输入流
            inStream.close();
            data = outStream.toByteArray();
            BASE64Encoder encoder = new BASE64Encoder();
            // 返回Base64编码过的字节数组字符串
            //System.out.println(encoder.encode(data));
            return encoder.encode(data);
        } catch (IOException e) {
            e.printStackTrace();
            return "";

        }
        // 对字节数组Base64编码

    }

}